package ua.races.servlet.listener;

import ua.races.dao.RacesDaoImpl;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

public class DaoServletContextListener implements ServletContextListener {

    private static final Logger log = Logger.getLogger(DaoServletContextListener.class.getName());
    private ServletContext context = null;
    RacesDaoImpl dao = null;
    HashMap<String, String> commands = null;

    /*
    * This method is invoked when the Web Application has been removed
    * and is no longer able to accept requests
    */

    public void contextDestroyed(ServletContextEvent event) {
        this.context = null;
        try {
            dao.stop();
        } catch (SQLException e) {
            log.error(e);
        }
        dao = null;
        commands = null;
        log.info("Context is destroying");
    }


    /**
     * This method is invoked when the Web Application
     * is ready to service requests
     */
    public void contextInitialized(ServletContextEvent event) {

        dao = new RacesDaoImpl();
        commands = ua.races.dom.command.Analyzer.buildMap();
        BasicConfigurator.configure();
        this.context = event.getServletContext();

        try {
            dao.start();
            this.context.setAttribute("DAO", dao);
            this.context.setAttribute("commands", commands);
        } catch (SQLException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }

        log.info("Context was built!");

    }
}